package com.ruoyi.business.timer;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.WxUserFace;
import com.ruoyi.business.domain.vo.HIKUserFace;
import com.ruoyi.business.service.IWxFaceDeviceService;
import com.ruoyi.business.service.IWxUserFaceService;
import com.ruoyi.business.service.impl.HikVisionServiceImpl;
import com.ruoyi.business.vo.*;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Component
@EnableScheduling
public class HikDeviceJobTimer {

    @Autowired
    @Qualifier("HikVisionService")
    private HikVisionServiceImpl hikVisionService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IWxUserFaceService wxUserFaceService;

    public static boolean isHandlingHikJobs = false;

    public static final Logger log = LoggerFactory.getLogger(HikDeviceJobTimer.class);


    private List<HIKUserFace> getHikJobsFromRedis() {
        List<HIKUserFace> deviceJobs = new ArrayList<>();;

        if (redisCache.redisTemplate.hasKey("HIK_FACE_DEVICE_JOBS")) {
            List<HIKUserFace> tempList = redisCache.getCacheList("HIK_FACE_DEVICE_JOBS");
            if (tempList != null && !tempList.isEmpty()) {
                deviceJobs = tempList;
            }
        }
        return  deviceJobs;
    }

    @Scheduled(cron = "*/58 * * * * ?")
    public void handleHikJobs() {
        if (isHandlingHikJobs) {
            log.info("正在处理中...");
            return;
        }
        isHandlingHikJobs = true;
        log.info("开始处理海康任务");
        List<HIKUserFace> hikJobsFromRedis = getHikJobsFromRedis();
        try {
            redisCache.deleteObject("HIK_FACE_DEVICE_JOBS");

            ArrayList<UserInfo> infos = new ArrayList<>();
            UserInfoOut userInfoOut;
            ArrayList<HIKUserFace> fails = new ArrayList<>();
            String personUuid = null;

            for (HIKUserFace item : hikJobsFromRedis) {
                infos.clear();
                userInfoOut = null;
                personUuid = UUID.randomUUID().toString().replaceAll("-", "");
                infos.add(new UserInfo(personUuid,
                        item.getUserId() + item.getName(), new Valid("2017-01-01T00:00:00", "2050-12-31T23:59:59")));
                log.info("新增人员...");
                List<UserInfoOut> result = hikVisionService.addPerson(infos, item.getHikDeviceIndex()).getUserInfoOut();
                if (!result.isEmpty()) {
                    userInfoOut = result.get(0);
                }
                if (userInfoOut == null) {
                    fails.add(item);
                    log.error("添加人员异常" + result.toString());
                    continue;
                }
                FaceInfo staticFD = new FaceInfo(userInfoOut.getEmployeeNo(), "blackFD");
                log.info("新增人脸...");
                ResponseStatus responseStatus = hikVisionService.addFace(staticFD, item.getHikDeviceIndex(), (RuoYiConfig.getUploadPath() + item.getResource()).replace("/profile/upload", ""));
                if (responseStatus.getStatusCode() != 1) {
                    fails.add(item);
                    hikVisionService.deletePerson(infos, item.getHikDeviceIndex());
                    log.error("添加人脸异常" + responseStatus.toString());
                    continue;
                }
                WxUserFace wxUserFace = wxUserFaceService.selectWxUserFaceByFaceId(item.getFaceId());
                wxUserFace.setDispatchStatus("2");
                wxUserFace.setDispatchDate(DateUtils.getNowDate());
                List<String> strings = new ArrayList<>();
                if (StringUtils.isNotEmpty(wxUserFace.getBindingDispatchUuids())) {
                    String[] split = wxUserFace.getBindingDispatchUuids().split(",");
                    strings = new ArrayList<>(Arrays.asList(split));
                }
                strings.add(personUuid);
                wxUserFace.setBindingDispatchUuids(String.join(",", strings));
                log.info("更新...");
                try {
                    wxUserFaceService.updateWxUserFace(wxUserFace);
                } catch (Exception e) {
                    fails.add(item);
                    hikVisionService.deletePerson(infos, item.getHikDeviceIndex());
                }
            }
            if (!fails.isEmpty()) {
                wxUserFaceService.handleFailFaceList(fails);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            isHandlingHikJobs = false;
            log.info("结束处理海康任务");
        }

    }

}
